<template>
  <div class="main-box">
    <div class="amap-page-container">
      <!-- <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box> -->
      <el-amap class="amap-box" :zoom="zoom" :center="center" :events="events" :plugin="plugin" pitch-enable="false">
        <el-amap-marker
          v-for="marker in markers"
          :position="marker.position"
          :key="marker.id"
          :events="marker.events"
          :icon="marker.icon"
        ></el-amap-marker>
        <el-amap-info-window
          v-if="window"
          :position="window.position"
          :visible="window.visible"
          :content="window.content"
          :offset="window.offset"
          :close-when-click-map="true"
          :is-custom="true"
        >
          <div class="info-window">
            <div class="cell-header">
              <div class="number">
                <span class="icon-circle">{{ window.carInfo.carType }}</span>
                <span>{{ window.carInfo.carNumber }} ({{ window.carInfo.seats }}座)</span>
              </div>
              <span :class="['status', carOperateStatus[window.carInfo.carRunStatus].color]">
                {{ carOperateStatus[window.carInfo.carRunStatus].name }}
              </span>
            </div>
            <div class="cell-content">
              <div class="cell-item" v-for="(item, index) in window.carInfo.attr" :key="index">
                <span class="label">{{ item.label }}：</span>
                <span :class="['value', item.color]">{{ item.value }}</span>
              </div>
            </div>
            <div class="cell-footer">最后上报时间：{{ window.carInfo.updateTime }}</div>
          </div>
        </el-amap-info-window>
      </el-amap>
    </div>
    <div class="feature-box">
      <div class="search">
        <el-input placeholder="搜索车牌号码" v-model="searchCarNumber" class="input-with-select" clearable></el-input>
      </div>
      <div class="car-info">
        <div class="title">
          <div>
            实时数据
            <span class="blue">({{ window.visible && carInfoObj.carNumber ? carInfoObj.carNumber : '请先选中车辆' }})</span>
          </div>
          <div class="update-time">
            最后上报时间：
            <span class="blue">{{ window.visible ? carInfoObj.updateTime : '暂无' }}</span>
          </div>
          <div class="address">当前位置：{{ window.visible ? carAddress : '暂无' }}</div>
        </div>
        <el-collapse class="collapse-box" v-model="activeNames">
          <el-collapse-item title="车辆操作" name="1">
            <el-button size="small" v-for="(item, index) in operateBtns" :key="index" :loading="item.loading" @click="doOperate(item.type, index)">
              {{ item.name }}
            </el-button>
            <!-- <el-button size="small">重置密码</el-button> -->
          </el-collapse-item>
          <el-collapse-item title="车辆详情" name="2">
            <div class="cell-box">
              <div class="cell-item" v-for="(item, index) in carInfoObj.attrs" :key="index">
                <span class="label">{{ item.label }}：</span>
                <span :class="['value', item.color]">{{ item.value }}</span>
              </div>
            </div>
          </el-collapse-item>
          <el-collapse-item title="车辆运营" name="3">
            <div class="cell-box">
              <div class="cell-item" v-for="(item, index) in carInfoObj.operate" :key="index">
                <span class="label">{{ item.label }}：</span>
                <span :class="['value', item.color]">{{ item.value }}</span>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <div v-if="dialogObj.isShow">
      <c-dialog
        width="80%"
        class="park-dialog"
        fullscreen
        :is-show="dialogObj.isShow"
        :title="dialogObj.title"
        close-btn
        :no-btn="dialogObj.noBtn"
        @before-close="dialogObj.isShow = false"
      >
        <map-track ref="childRef" :show-type="dialogObj.showType" :init-data.sync="dialogObj.initData"></map-track>
      </c-dialog>
    </div>
  </div>
</template>

<script>
import dictObj from '@/store/dictData'
import CDialog from 'components/dialog'
import MapTrack from './vehicle/operate/map-track'
import utils from 'utils'

const iconObj = {
  empty: require('images/user-car/empty.png'),
  offline: require('images/user-car/offline.png'),
  useCar: require('images/user-car/online.png'),
  ordered: require('images/user-car/online.png'),
  repair: require('images/user-car/repair.png')
}
export default {
  components: {
    CDialog,
    MapTrack
  },
  data(vm) {
    return {
      searchCarNumber: '', // 搜索车牌
      dialogObj: {},
      operateBtns: [
        {
          type: 'findCar',
          loading: false,
          name: '鸣笛'
        },
        {
          type: 'setPassword',
          loading: false,
          name: '密码'
        },
        {
          type: 'openDoor',
          loading: false,
          name: '开锁'
        },
        {
          type: 'closeDoor',
          loading: false,
          name: '关锁'
        },
        {
          type: 'powerOn',
          loading: false,
          name: '通电'
        },
        {
          type: 'powerOff',
          loading: false,
          name: '断电'
        },
        {
          type: 'openLight',
          loading: false,
          name: '开灯'
        },
        {
          type: 'closeLight',
          loading: false,
          name: '关灯'
        },
        {
          type: 'openAcc',
          loading: false,
          name: '启动'
        },
        {
          type: 'closeAcc',
          loading: false,
          name: '熄火'
        },
        {
          type: 'closeWindow',
          loading: false,
          name: '关窗'
        },
        {
          type: 'queryCarStatus',
          loading: false,
          name: '刷新'
        },
        {
          type: 'openAir',
          loading: false,
          name: '开空调'
        },
        {
          type: 'closeAir',
          loading: false,
          name: '关空调'
        },
        {
          type: 'openBoot',
          loading: false,
          name: '开尾箱'
        },
        // {
        //   type: 'carTrack1',
        //   loading: false,
        //   name: '跟踪'
        // },
        {
          type: 'carTrack',
          loading: false,
          name: '查看轨迹'
        }
      ],
      carOperateStatus: dictObj.carOperateStatus,
      initCenter: [],
      center: [114.124592, 22.648286],
      zoom: 11, // 地图放大倍数
      pageNo: 1,
      pageSize: 9999,
      carAddress: '', // 车辆当前位置信息
      carList: [], // 所有车列表
      carInfoObj: {}, // 点击marker时车的信息
      markers: [], // 地图上车图
      initMakders: [], // 搜索之前markers
      windows: [], // 地图弹框信息集合
      window: '', // 当前车弹框信息
      windowIndex: '', // 当前弹框的下标
      activeNames: [], // 右侧折叠板状态
      // isLoading: false, // 车辆操作状态
      // searchOption: {
      //   city: '全国',
      //   citylimit: true
      // },
      plugin: [
        'ToolBar',
        'Scale'
        // {
        //   pName: 'Geolocation',
        //   events: {
        //     init() {},
        //     complete: () => {
        //       //定位成功
        //       // var address = result.formattedAddress
        //       // var point = result.position
        //       // var obj = {
        //       //   address: address,
        //       //   name: '',
        //       //   location: point
        //       // }
        //       // vm.list = [obj]
        //       // vm.makerConf.position = [point.lng, point.lat]
        //     },
        //     error: err => {
        //       console.log(err)
        //     }
        //   }
        // }
      ],
      events: {
        click: () => {
          if (vm.window.visible) {
            vm.window.visible = false
            vm.carInfoObj = {}
            vm.activeNames = []
            vm.carAddress = ''
          }
        }
      }
    }
  },
  watch: {
    searchCarNumber(newVal, oldVal) {
      if (newVal !== oldVal && newVal.length > 1) {
        const curCarList = this.initMarkers.slice()
        this.markers = curCarList.filter(val => val.carNumber.indexOf(newVal) >= 0)
        if (this.markers.length) {
          this.center = this.markers[0].position
        }
      }
      if (oldVal && !newVal) {
        this.markers = this.initMarkers
        this.center = this.initCenter
      }
    }
  },
  methods: {
    getCarAddress(center) {
      const geocoder = new AMap.Geocoder({
        radius: 100,
        extensions: 'all'
      })
      geocoder.getAddress(center, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          if (result && result.regeocode) {
            this.carAddress = result.regeocode.formattedAddress
          }
        }
      })
    },
    getCarList(operateType, carNumber) {
      this.$api.vehicle
        .fetch('carMrgRunList', {
          rows: this.pageNo,
          offset: this.pageSize
        })
        .then(val => {
          const { data, totalCount } = val
          const markers = []
          const windows = []
          const carInfoList = []
          if (data && totalCount) {
            data
              .filter(res => res.carRunLongitude && res.carRunLatitude)
              .forEach((item, index) => {
                const that = this
                const isOnline = new Date().getTime() - new Date(item.updateTime).getTime() > 15 * 60 * 1000 || !item.updateTime
                const carInfo = {
                  updateTime: item.updateTime,
                  carNumber: item.carNumber,
                  carType: item.category === 1 ? '电' : '油',
                  carRunStatus: item.carRunStatus,
                  seats: item.seats,
                  attr: [
                    {
                      label: '型号',
                      value: `${item.carTypeBrance}(${item.carTypeTypeName || ''})`
                    },
                    {
                      label: item.category === 1 ? '电量' : '油量',
                      value: `${item.restBattery} %`,
                      color: item.restBattery < 30 ? 'red' : item.restBattery > 70 ? 'green' : 'yellow'
                    },
                    {
                      label: '速度',
                      value: `${item.carRunSpeed} KM/H`
                    },
                    {
                      label: '续航',
                      value: `${item.enduranceMileage} KM`
                    }
                  ]
                }
                const carAllAttrs = [
                  {
                    label: '车牌号码',
                    value: item.carNumber
                  },
                  {
                    label: '是否在线',
                    value: isOnline ? '离线' : '在线',
                    color: isOnline ? 'red' : ''
                  },
                  {
                    label: '小电瓶电压',
                    value: `${item.smallBatteryVoltage ? item.smallBatteryVoltage + 'V' : ''}`,
                    color: item.smallBatteryVoltage < 10 ? 'red' : 'green'
                  },
                  {
                    label: item.category === 1 ? '车辆电量' : '车辆油量',
                    value: `${item.restBattery} %`,
                    color: item.restBattery < 30 ? 'red' : item.restBattery > 70 ? 'green' : 'yellow'
                  },
                  {
                    label: '行驶总里程',
                    value: `${parseInt(item.mileage)} KM`
                  },
                  {
                    label: '剩余续航',
                    value: `${item.enduranceMileage} KM`
                  },
                  {
                    label: '车门状态',
                    value: item.doorStatus === '0' ? '关门' : item.doorStatus === '1' ? '开门' : '未知'
                  },
                  {
                    label: '车辆密码',
                    value: item.carPassword
                  },
                  {
                    label: '发动机状态',
                    value: item.carSignal === '1' ? '启动' : '熄火',
                    color: item.carSignal === '1' ? 'green' : ''
                  },
                  {
                    label: '车辆速度',
                    value: `${item.carRunSpeed} KM/H`
                  },
                  {
                    label: '充电状态',
                    value: item.batStatus === 1 ? '充电中' : '未充电'
                  },
                  {
                    label: '车架号尾号',
                    value: item.classno.substr(item.classno.length - 6)
                  },
                  {
                    label: '设备编号',
                    value: item.cid
                  },
                  {
                    label: 'SIM卡号',
                    value: item.phone
                  }
                ]
                const operate = [
                  {
                    label: '所属企业',
                    value: item.companyName
                  },
                  {
                    label: '车辆状态',
                    value: this.carOperateStatus[item.carRunStatus].name
                  },
                  {
                    label: '锁定状态',
                    value: item.isLockCar === 1 ? '已锁定' : '未锁定',
                    color: item.isLockCar === 1 ? 'red' : ''
                  },
                  {
                    label: '投放网点',
                    value: item.parkName || '暂无'
                  },
                  {
                    label: '还车网点',
                    value: item.returnParkName || '暂无'
                  }
                ]
                markers.push({
                  position: [item.carRunLongitude, item.carRunLatitude],
                  icon: iconObj[item.carRunStatus], //不设置默认蓝色水滴
                  carNumber: item.carNumber,
                  events: {
                    click() {
                      that.getCarAddress([item.carRunLongitude, item.carRunLatitude])
                      // 方法：鼠标移动到点标记上，显示相应窗体
                      that.windows.forEach(window => {
                        window.visible = false // 关闭窗体
                      })
                      that.window = that.windows[index]
                      that.$nextTick(() => {
                        that.window.visible = true
                      })
                      that.carInfoObj = that.carList[index]
                      that.windowIndex = index
                      that.activeNames = ['1', '2', '3']
                    }
                  }
                })
                windows.push({
                  position: [item.carRunLongitude, item.carRunLatitude],
                  isCustom: true,
                  offset: [-2, -40], // 窗体偏移
                  showShadow: false,
                  visible: false, // 初始是否显示,
                  carInfo
                })
                carInfoList.push({
                  carRunLongitude: item.carRunLongitude,
                  carRunLatitude: item.carRunLatitude,
                  updateTime: item.updateTime,
                  carNumber: item.carNumber,
                  attrs: carAllAttrs,
                  operate
                })
                // 操作车辆时弹框和操作车辆区域的数据刷新
                if (operateType === 'setPassword' || operateType === 'queryCarStatus') {
                  if (item.carNumber === carNumber) {
                    this.window = windows[index]
                    this.carInfoObj = carInfoList[index]
                    this.$nextTick(() => {
                      this.window.visible = true
                    })
                  }
                }
              })
            // 车辆信息
            this.carList = carInfoList
            //  加点
            this.markers = markers
            this.initMarkers = markers
            // 加弹窗
            this.windows = windows
          }
        })
    },
    // 获取网点列表
    getParkList() {
      const { pageNo, pageSize } = this.pageInfo
      this.$api.outlets
        .fetch('parkList', {
          rows: pageNo,
          offset: pageSize
        })
        .then(res => {
          if (res && res.totalCount) {
            const { data } = res
            this.parkList = data || []
          } else {
            this.parkList = res || []
          }
        })
    },
    // 操作车辆
    doOperate(operateType, index) {
      const { carNumber, carRunLongitude, carRunLatitude } = this.carInfoObj
      if (!carNumber) {
        return this.$msgTip('请先选择车辆', 'warning')
      }
      if (operateType === 'carTrack' || operateType === 'carTrack1') {
        // 查看车辆轨迹
        if (!carRunLongitude || !carRunLatitude) {
          return this.$msgTip('暂无车辆位置信息', 'warning')
        }
        this.dialogObj = {
          isShow: true,
          noBtn: true,
          showType: operateType === 'carTrack' ? 1 : 2,
          title: `查看车辆轨迹（${carNumber}）`,
          initData: this.carInfoObj
        }
        return false
      }
      utils.confirmTip(`确认执行${dictObj.carOperateType[operateType]}操作`, () => {
        const { userName } = this.$store.getters
        this.operateBtns[index].loading = true
        let params = {}
        if (operateType === 'openAir') {
          params = {
            temperature: 24
          }
        }
        this.$api.vehicle
          .fetch('openTheDoor', { operateType, carNumber, dispatcherName: userName, ...params }, { hasErrMsg: true })
          .then(res => {
            const { code, message } = res
            this.operateBtns[index].loading = false
            if (code === 0) {
              this.$msgTip(`${dictObj.carOperateType[operateType]}成功`)
              if (operateType === 'setPassword' || operateType === 'queryCarStatus') {
                this.getCarList(operateType, carNumber)
              }
            } else {
              this.$msgTip(message)
            }
          })
          .catch(() => {
            this.operateBtns[index].loading = false
          })
      })
    },
    onSearchResult(pois) {
      console.log(pois)
      // this.result = pois
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi
          lngSum += lng
          latSum += lat
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.center = [center.lng, center.lat]
      }
    },
    initData() {
      const cityInfo = utils.getStore('cityInfo')
      if (cityInfo) {
        const { longitude, latitude } = cityInfo
        if (latitude) {
          this.initCenter = [longitude, latitude]
          this.center = this.initCenter.slice()
        }
      }
      this.getCarList()
    }
  },
  created() {
    this.initData()
  }
}
</script>
<style lang="less" scoped>
.main-box {
  display: flex;
  .amap-page-container {
    position: relative;
    flex: 9;
    height: calc(100vh - 84px);
    margin: 10px 10px;
  }
  .search-box {
    position: absolute !important;
    top: 10px;
    right: 20px;
    z-index: 1;
    padding: 0 20px;
    margin-top: 10px;
    color: @active;
    border: 1px solid @border-default;
    border-radius: 10px;
  }
  .info-window {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 240px;
    min-height: 100px;
    padding: 10px 5px;
    background-color: @white;
    border: 1px solid @primary-color;
    border-radius: 8px;
    &::before {
      position: absolute;
      bottom: -12px;
      left: 110px;
      width: 0;
      height: 0;
      content: '';
      border: 10px solid;
      border-color: @primary-color transparent transparent;
    }
    &::after {
      position: absolute;
      bottom: -10px;
      left: 110px;
      width: 0;
      height: 0;
      content: '';
      border: 10px solid;
      border-color: @white transparent transparent;
    }

    .cell-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 5px 10px;
      font-size: @f14;
      color: @label-color;
      .number {
        display: flex;
        align-items: center;
      }

      .status {
        font-size: @f12;
        color: @primary-color;
      }
    }
    .cell-content {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      padding: 5px 0;
      margin: 5px 10px;
      border-top: 1px dotted @border-default;
      border-bottom: 1px dotted @border-default;
      .cell-item {
        display: flex;
        align-items: center;
        min-width: 100px;
        font-size: @f12;
        .value {
          color: @primary-color;
        }
      }
    }
    .cell-footer {
      margin: 5px 10px;
      font-size: @f12;
    }
  }
  .feature-box {
    flex: 2;
    margin: 10px 10px 10px 0;
    .search {
      margin-bottom: 10px;
    }
    .car-info {
      padding: 0 10px;
      background-color: @white;
      border: 1px solid @border-default;
      border-radius: 8px;
      .title {
        min-height: 60px;
        font-size: @f16;
        font-weight: bold;
        line-height: 40px;
        color: @label-color;
        .update-time,
        .address,
        .company {
          margin-bottom: 10px;
          font-size: @f12;
          font-weight: normal;
          line-height: 14px;
        }
      }
      .collapse-box {
        .el-button--small {
          margin: 0 10px 10px 0;
        }
        .cell-box {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .cell-item {
            min-width: 130px;
            font-size: @f12;
            .value {
              color: @primary-color;
            }
          }
        }
      }
    }
  }
}
</style>
